<template>
  <div class="tableTree">
    <div class="tableHead">
      <table>
        <tr>
          <td class="td1"><span>{{title}}</span></td>
          <td class="td2"><span>类型</span></td>
          <td class="td3"><span>必填</span></td>
          <td class="td4"><span>示例</span></td>
          <td class="td5"><span>说明</span></td>
          <td class="td6"><span>限制</span></td>
          <td class="td7"><span>操作</span></td>
        </tr>
      </table>
    </div>
    <div class="tableBody" ref="tableBox">
      <table v-if="treeDataSource.length > 0">
        <tbody>
        <tr>
          <td>
            <tree-item v-for="(item, index) of treeDataSource"
               :key="index"
               :tableNum="treeDataSource.length"
               :tableBtn="tableBtn"
               :tableLength="treeDataSource.length"
               @handlerExpand="handlerExpand"
               @handelClickRowEdit="handelClickRowEdit"
               @removeNode="removeNode"
               @addRow="addRow"
               @addRowChildren="addRowChildren"
               @insertDataStructure="insertDataStructure"
               @removeDataInit="removeDataInit"
               @handelClickDisassociate="handelClickDisassociate"
               :dataRow="item"
               :root="0">
            </tree-item>
          </td>
        </tr>
        </tbody>
      </table>
    </div>
    <el-dialog
      v-if="dialogVisibleseeView"
      custom-class="dhcWebLayer"
      top="0"
      :close-on-click-modal="false"
      title="引用数据结构"
      :visible.sync="dialogVisibleseeView"
      width="30%">
      <el-table
        :data="datatableData"
        size="small"
        stripe
        class="elementTable"
        ref="multipleTable"
        @select-all="onSelectAll"
        @selection-change="selectItem"
        @row-click="onSelectOp"
        @cell-mouse-enter="hovercell"
        header-cell-class-name="elementTableHeader"
        cell-class-name="elementTableBody"
        highlight-current-row
        >
        <el-table-column align="center" type="selection" :selectable="seletiontable" width="55"></el-table-column>
        <el-table-column prop="name" align="center" label="数据结构名称">
          <template slot-scope="scope">
            <span>{{scope.row.name}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="描述" ></el-table-column>
        <el-table-column prop="type" label="类型" width="200"></el-table-column>
      </el-table>
      <div style="margin-top: 16px;text-align: right;">
        <el-button size="small" type="primary" @click="datahoversave">确定</el-button>
        <el-button size="small" @click="dialogVisibleseeView = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getdatastructureList, Editdatastructure } from '@/api/apiModel/api.js'
  export default {
    components: {
      treeItem: () => import('./tableItem.vue')
    },
    props: ['list', 'tableBtn', 'title', 'dataStructuretype', 'fdataStructureIds'],
    data() {
      return {
        dialogVisibleseeView: false,
        datatype: '',
        datatableData: [],
        ednowData: '',
        datahover: false,
        selectlist: [],
        datastructure: [], // 引用数据结构子数组
        datastruct: [], // 引用数据结构列表数据
        dataStructureIds: [], // 数据结构ID
        datastructureList: {
          'condition': [
          ],
          'sort': [
            {
              'direction': 'DESC',
              'property': 'ctime'
            }
          ],
          'fields': []
        },
        nowData: [
          {
            id: '10000000000',
            parentId: null,
            parameterName: '',
            type: '',
            required: true,
            example: '',
            explain: '',
            limit: '',
            children: [
              {
                id: '11000000000',
                parentId: '10000000000',
                parameterName: '',
                type: '',
                required: true,
                example: '',
                explain: '',
                limit: '',
                children: []
              }
            ]
          },
          {
            id: '20000000000',
            parentId: null,
            parameterName: '',
            type: '',
            required: true,
            example: '',
            explain: '',
            limit: '',
            children: []
          }
        ],
        treeDataSource: [],
        oldRow: {},
        charsReq: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
      }
    },
    created() {
      this.initTreeData(this.list)
      this.dataStructureIds = this.fdataStructureIds
    },
    mounted() {
      document.addEventListener('click', e => {
        try {
          if (!this.$refs.tableBox.contains(e.target)) {
            this.$emit('handelClickRowEdit', this.oldRow, this.oldRow)
          }
        } catch (e) {}
      })
    },
    watch: {
      dataStructuretype(val, oldVal) {
        this.datatype = ''
        this.datatype = val
      }
    },
    methods: {
      datahoversave() {
        this.dataStructureIds.push(this.datastruct.id)
        this.dataarrqc(this.dataStructureIds)
        this.$emit('StructureID', this.dataStructureIds)
        this.abc(this.ednowData)
        this.dialogVisibleseeView = false
      },
      dataarrqc(arr) {
        const hash = []
        for (var i = 0; i < arr.length; i++) {
          if (hash.indexOf(arr[i]) == -1) {
            hash.push(arr[i])
          }
        }
        this.dataStructureIds = hash
        return hash
      },
      abc(row) {
        this.eachNewData(this.nowData)
        const uuidNum = this.generateMixedReq(30)
        this.nowData.map((val, index) => {
          if (index === 0) {
            val.StructureID = this.datastruct.id
            val.headerGroup = 'qwertyuiop'
          }
          val.colorBg = 'qwertyuiop'
          val.parentId = row.parentId
          val.uuid = uuidNum
        })
        this.insertDataList(this.treeDataSource, row)
        this.initTreeData(this.treeDataSource)
      },
      insertDataStructure(row) {
        // 引用数据结构
        this.$emit('insertStructure')
        this.ednowData = row
        // this.datatype = ''
        // this.datatype = this.dataStructuretype
        this.dialogVisibleseeView = true
        getdatastructureList(this.datastructureList, 0, '').then(res => {
          this.datatableData = res.data.data.records
        })
      },
      generateMixedReq(n) {
        var res = ''
        for (var i = 0; i < n; i++) {
          var id = Math.ceil(Math.random() * 35)
          res += this.charsReq[id]
        }
        return res
      },
      getTableData() {
        return this.treeDataSource
      },
      initTreeData(list) {
        let tempData = JSON.parse(JSON.stringify(list))
        let reduceDataFunc = (data, level) => {
          data.map((m, i) => {
            m.isExpand = !!m.isExpand
            m.editRow = !!m.editRow
            m.children = m.children || []
            m.level = level
            m.pleft = (level - 1) * 20
            if (m.children.length > 0) {
              reduceDataFunc(m.children, level + 1)
            }
          })
        }
        reduceDataFunc(tempData, 1)
        this.treeDataSource = tempData
      },
      handlerExpand(row) { // 点击展开闭合按钮
        this.$emit('handlerExpand', row)
      },
      handelClickRowEdit(row) {
        if (row.id === this.oldRow.id) {
          this.oldRow = {}
        }
        this.$emit('handelClickRowEdit', row, this.oldRow)
        this.oldRow = row
      },
      removeNode(row) {
        this.treeDataSource = this.filterReq(this.treeDataSource, row.id)
      },
      removeDataInit(row) {
        if (row.parentId === null) {
          this.treeDataSource = this.treeDataSource.filter(val => {
            return val.uuid !== row.uuid
          })
        } else {
          this.removeDataInitForEach(this.treeDataSource, row)
        }
      },
      removeDataInitForEach(data, row) {
        const _this = this
        data.forEach(val => {
          if (val.id === row.parentId) {
            val.children = val.children.filter(val => {
              return val.uuid !== row.uuid
            })
          } else if (val.children.length > 0) {
            _this.removeDataInitForEach(val.children, row)
          }
        })
      },
      filterReq(data, id) {
        const _this = this
        var newData = data.filter(x => x.id !== id)
        newData.forEach(x => x.children && (x.children = _this.filterReq(x.children, id)))
        return newData
      },
      addRow(row) {
        this.recursionData(this.treeDataSource, row)
      },
      recursionData(data, row) {
        const _this = this
        // 如果当前目标节点的 pid 为null  则在数组最外层push一条数据
        if (row.parentId === null) {
          this.treeDataSource.push({
            id: _this.generateMixedReq(32),
            parentId: null,
            parameterName: '',
            type: '',
            required: true,
            example: '',
            explain: '',
            limit: '',
            children: [],
            isExpand: false,
            editRow: false,
            level: 1,
            pleft: 0
          })
        } else {
          data.forEach(val => {
            if (val.id === row.parentId) {
              val.children.push({
                id: _this.generateMixedReq(32),
                parentId: val.id,
                parameterName: '',
                type: '',
                required: true,
                example: '',
                explain: '',
                limit: '',
                children: [],
                isExpand: false,
                editRow: false,
                level: val.level + 1,
                pleft: val.level * 20
              })
            } else if (val.children.length > 0) {
              this.recursionData(val.children, row)
            }
          })
        }
      },
      addRowChildren(row) {
        this.recursionChildren(this.treeDataSource, row)
      },
      recursionChildren(data, row) {
        const _this = this
        data.forEach((val, index) => {
          if (val.id === row.id) {
            val.children.push({
              id: _this.generateMixedReq(32),
              parentId: val.id,
              name: _this.generateMixedReq(5),
              age: '',
              date: '',
              children: [],
              isExpand: false,
              editRow: false,
              level: val.level + 1,
              pleft: val.level * 20
            })
          } else if (val.children.length > 0) {
            this.recursionChildren(val.children, row)
          }
        })
      },
      eachNewData(data) {
        const _this = this
        data.forEach((val, index) => {
          val.allDataIdent = 'qwertyuiop'
          if (val.children.length > 0) {
            _this.eachNewData(val.children)
          }
        })
      },
      insertDataList(data, row) {
        const _this = this
        if (row.parentId === null) {
          _this.treeDataSource = _this.treeDataSource.concat(_this.nowData)
        } else {
          data.forEach(val => {
            if (val.id === row.parentId) {
              val.children = val.children.concat(_this.nowData)
            } else if (val.children.length > 0) {
              this.insertDataList(val.children, row)
            }
          })
        }
      },
      handelClickDisassociate(row) {
        this.$confirm('是否要独立保存该数据结构的信息到API文档中，并且取消该数据结构与API文档的关联？\n' +
          '取消与数据结构的关联之后，数据结构的改动将不会再同步到API文档中。', '取消该数据结构的关联', { type: 'warning' }).then(() => {
          if (row.parentId === null) {
            this.uuidDataFunc(this.treeDataSource, row)
          } else {
            this.disassociateForEach(this.treeDataSource, row)
          }
          const _this=this
          var arr = this.dataStructureIds
          var b = row.StructureID
          var newArr = arr.filter(item => item != b)
          _this.dataStructureIds = newArr
          this.$emit('StructureID', _this.dataStructureIds)
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // })
        })
      },
      uuidDataFunc(data, row) {
        const _this = this
        data.forEach(val => {
          if (val.uuid === row.uuid) {
            val.colorBg = null
            val.headerGroup = null
            val.allDataIdent = null
            val.id = _this.generateMixedReq(32)
            if (val.children.length > 0) {
              _this.valChildrenFun(val.children, val.id)
            }
          }
        })
      },
      valChildrenFun(data, pId) {
        const _this = this
        data.forEach(valC => {
          valC.colorBg = null
          valC.headerGroup = null
          valC.allDataIdent = null
          valC.id = _this.generateMixedReq(32)
          valC.parentId = pId
          if (valC.children.length > 0) {
            _this.valChildrenFun(valC.children, valC.id)
          }
        })
      },
      uuidDataFunChild(data, row) {

      },
      seletiontable(row, index) {
        if (this.datatype == 'FormData') {
          if (row.type == 'FormData') {
            return true
          } else {
            return false
          }
        } else if (this.datatype == 'JSON') {
          if (row.type == 'FormData') {
            return false
          } else if (row.type == 'Object') {
            return false
          } else if (row.type == 'Array') {
            return false
          } else if (row.type == 'XML') {
            return false
          } else {
            return true
          }
        } else if (this.datatype == 'XML') {
          if (row.type == 'FormData') {
            return false
          } else if (row.type == 'Object') {
            return false
          } else if (row.type == 'Array') {
            return false
          } else if (row.type == 'JSON') {
            return false
          } else {
            return true
          }
        } else {
          return false
        }
      },
      onSelectAll() {
        this.$refs.multipleTable.clearSelection()
      },
      selectItem(rows) {
        if (rows.length > 1) {
          var newRows = rows.filter((it, index) => {
            if (index == rows.length - 1) {
              this.$refs.multipleTable.toggleRowSelection(it, true)// 这行可以不要
              Editdatastructure(it.id).then(res => {
                this.nowData = res.data.data.content
                this.datastruct = res.data.data
              })
              return true
            } else {
              this.$refs.multipleTable.toggleRowSelection(it, false)
              Editdatastructure(it.id).then(res => {
                this.nowData = res.data.data.content
                this.datastruct = res.data.data
              })
              return false
            }
          })
          this.selectlist = newRows
        } else {
          this.selectlist = rows
          Editdatastructure(rows[0].id).then(res => {
            this.nowData = res.data.data.content
            this.datastruct = res.data.data
          })
        }
      },
      onSelectOp(row) {
        // this.$refs.multipleTable.clearSelection();不需要
        if (this.datatype == 'FormData') {
          if (row.type == 'FormData') {
            this.$refs.multipleTable.toggleRowSelection(row, true)// 有这个就够了，因为一旦勾选的内容有变化，那么就会触发selectItem(rows)这个函数
            Editdatastructure(row.id).then(res => {
              this.datastructure = res.data.data.content
            })
          }
        }
        if (this.datatype == 'JSON') {
          if (row.type == 'JSON') {
            this.$refs.multipleTable.toggleRowSelection(row, true)// 有这个就够了，因为一旦勾选的内容有变化，那么就会触发selectItem(rows)这个函数
            Editdatastructure(row.id).then(res => {
              this.datastructure = res.data.data.content
              this.datastruct = res.data.data
            })
          }
        }
        if (this.datatype == 'XML') {
          if (row.type == 'XML') {
            this.$refs.multipleTable.toggleRowSelection(row, true)// 有这个就够了，因为一旦勾选的内容有变化，那么就会触发selectItem(rows)这个函数
            Editdatastructure(row.id).then(res => {
              this.datastructure = res.data.data.content
              this.datastruct = res.data.data
            })
          }
        }
        // this.selectlist = [];不需要
        // this.selectlist.push(row);不需要
      },
      hovercell(row, column, cell, event) {
        if (this.datatype == 'FormData') {
          if (row.type == 'FormData') {
            this.datahover = true
          } else {
            this.datahover = false
          }
        }
        if (this.datatype == 'JSON') {
          if (row.type == 'JSON') {
            this.datahover = true
          } else {
            this.datahover = false
          }
        }
      },
      disassociateForEach(data, row) {
        const _this = this
        data.forEach(val => {
          if (val.uuid === row.uuid) {
            val.colorBg = null
            val.headerGroup = null
            val.allDataIdent = null
            val.id = _this.generateMixedReq(32)
            if (val.children.length > 0) {
              _this.valChildrenFun(val.children, val.id)
            }
          } else if (val.children.length > 0) {
            _this.disassociateForEach(val.children, row)
          }
        })
      }
    }
  }
</script>

<style>

</style>
